package com.mooc.ppjoke.ui.home;

import android.annotation.SuppressLint;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.lifecycle.MutableLiveData;
import androidx.paging.DataSource;
import androidx.paging.ItemKeyedDataSource;
import androidx.paging.PagedList;

import com.alibaba.fastjson.TypeReference;
import com.mooc.lib_network.ApiResponse;
import com.mooc.lib_network.ApiService;
import com.mooc.lib_network.JsonCallBack;
import com.mooc.lib_network.Request;
import com.mooc.ppjoke.data.Feed;
import com.mooc.ppjoke.ui.AbsViewModel;
import com.mooc.ppjoke.ui.MutableDataSource;
import com.mooc.ppjoke.ui.login.QQUserManager;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class HomeViewModel extends AbsViewModel<Feed> {
    private volatile boolean withCache=true;
    private MutableLiveData<PagedList<Feed>> cacheLVData=new MutableLiveData();
    private AtomicBoolean loadAfter=new AtomicBoolean(false);
    private String mFeedType;
    @Override
    public DataSource createDataSource() {
        return dataSource;
    }

    public MutableLiveData<PagedList<Feed>> getCacheLVData() {
        return cacheLVData;
    }

    private ItemKeyedDataSource<Integer,Feed> dataSource=new ItemKeyedDataSource<Integer, Feed>() {
        @Override
        public void loadInitial(@NonNull @NotNull LoadInitialParams<Integer> params, @NonNull @NotNull LoadInitialCallback<Feed> callback) {
            //初始化数据'
            loadData(0,params.requestedLoadSize, callback);
            withCache=false;
        }

        @Override
        public void loadAfter(@NonNull @NotNull LoadParams<Integer> params, @NonNull @NotNull LoadCallback<Feed> callback) {
            //分页
            loadData(params.key,params.requestedLoadSize, callback);
        }

        @Override
        public void loadBefore(@NonNull @NotNull LoadParams<Integer> params, @NonNull @NotNull LoadCallback<Feed> callback) {
            //上一页 向前加载
            callback.onResult(Collections.emptyList());
        }

        @NonNull
        @NotNull
        @Override
        public Integer getKey(@NonNull @NotNull Feed item) {
            return item.id;
        }
    };

    private void loadData(int key,int count, ItemKeyedDataSource.LoadCallback<Feed> callback) {
        if(key>0){
            loadAfter.set(true);
        }
//        queryHotFeedsList
        Request request = ApiService.get("/feeds/queryHotFeedsList");
        request.addParam("feedId", key);
        request.addParam("feedType",mFeedType);
        request  .addParam("pageCount",count);
        request .addParam("userId", QQUserManager.getInstance().getUserId());
        request.setResponseType(new TypeReference<ArrayList<Feed>>(){}.getType());
        if(withCache){
            request.setCacheStragtegy(Request.CACHE_ONLY);
            request.excute(new JsonCallBack<List<Feed>>(){
                @Override
                public void OnCacheSuccess(ApiResponse<List<Feed>> apiResponse) {
                    Log.i("OnCacheSuccess", "OnCacheSuccess: "+apiResponse.body.size());
                    List<Feed> body = apiResponse.body;
                    MutableDataSource dataSource=new MutableDataSource<Integer,Feed>();
                    dataSource.data.addAll(body);
                    PagedList pagedList = dataSource.buildPaagedList(config);
                    cacheLVData.postValue(pagedList);
                }
            });
        }
        try {
            Request netRequest = withCache ? request.clone() : request;
            netRequest.setCacheStragtegy(key == 0 ? Request.NET_CACHE : Request.NET_ONLY);
            ApiResponse<List<Feed>> response = netRequest.excute();
            List<Feed> data = response.body == null
                    ? Collections.emptyList() : response.body;

            callback.onResult(data);

            if (key > 0) {
                //通过BoundaryPageData发送数据 告诉UI层 是否应该主动关闭上拉加载分页的动画
                ((MutableLiveData) getBoundaryLiveData()).postValue(data.size() > 0);
                loadAfter.set(false);
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }


        Log.i("OnCacheSuccess", key+"");


    }
    public void setFeedType(String feedType) {

        mFeedType = feedType;
    }

    @SuppressLint("RestrictedApi")
    public void loadAfter(int id, ItemKeyedDataSource.LoadCallback<Feed> feedLoadCallback) {
        if(loadAfter.get()){
            feedLoadCallback.onResult(Collections.emptyList());
            return;
        }
        ArchTaskExecutor.getIOThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                loadData(id,config.pageSize, feedLoadCallback);
            }
        });
    }
}